package com.itbaizhan.utils;

import org.jose4j.json.JsonUtil;
import org.jose4j.jwa.AlgorithmConstraints;
import org.jose4j.jwk.JsonWebKey;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * jwt工具类
 */
public class JwtUtils {

    // 私钥
    public final static    String privatejson  = "{\"kty\":\"RSA\",\"n\":\"u8SyxKf2kLkmOKOU-mcbXQmacQDCPtxfMGKzYx6HWaGcCFbIrFDubGIWhe3GRP5uQqXekqwDtiqurdGfUzOLSSLfe7bmCmEgntNbF9bgk8lZUhzszmb4sGk6VK4YiOiTWGYWn_7jyKyF_OXEpXY4C3WWWsZwQfLPNUYfVZE76o1MXT9F3622RhLSPOFVqJYL6RlzllvNc2PdfzVEBnFU4wKszT0n9J8ZrNAnlNUxOXi7Y78fLqQks60ERznZwytwB8krydQGkjH9y9pf70QFJW228mUxXHnPhG87Gi2eE62TardkBCvQcm4TJlEB5dnmhFYFhRkAR6IznUAjtkFZIw\",\"e\":\"AQAB\",\"d\":\"LLVCjZGio0X6hEzq2Y54VPhG5jY0igwlvBscNHMd7ikNQm0LfgANLRBT5ZK-fUoJjeP5sXm0rojOK8P4SDLDLOhZRxc_AeSrhDW2AGCg-39bPbJ2bhTVjQeZJHWJkPuzrb4tD-58ZRkzFArPfkg-Qvg-EyIhs4oxbTFjn5ejqQ6PdTl_CuOFYPPNMmJcyZaglbD0VcQf09UAZ0DV5U8smN0iHmHKXotCK7KhSOgfhvU2ouqUY3emY6sUHtNBwaqoEf-19YNiE69FzJ9E7n6c5b8NQQ4iH0h21vFmmSqTmX1FSw_hWZ0n3GbNDj3Lm7X7PX5GoJ6dZ_3ekmfH4orzgQ\",\"p\":\"-nd4Q941C6xQmR6xrdLHrgs6yr4npJTJUh7dcv9mKjuzd81DZb54UwkECceCJQDGwXTwDX-LuzUUWfC7kOfaB04YbPqeOPDd26p2bJo2R1Y3LHY8wLV6ptPAPgVVnDuBl3muok7e8kvep5pvsFbOPx2ZmYnA3UUWLhzfth5BuqM\",\"q\":\"v-qiWGYs9W9SpY4tcCOkvjYKZXBXTpQPTpCpXa2KyWamxZTfp0BzuPdvmx-M5yTGZDSo-G9iRajdnwtTQGaimJxLmQgyhUn2p6geouRBu3lUuiQrNa0EILf2sku1jR43orkMKYny1a0dnZ2I8cqas-LmpcvtqAH-K4qXblnuT4E\",\"dp\":\"-BT3cTmaDvrZRiDJ2qLpFzGWRRR9zZ11nrplm67u8av6ghI0zIURRyWp80nCVYZkV1_NGYGY1I-pncA8-DU9lni65s6Bg2LITPiVndJNKvFxar-eQz49wxn_0y6TclDadj-XQrqeRx3w5s-oCuCgHpHh_tsbxc7VPk1pJEjpz8M\",\"dq\":\"HDb_pSVoaLD0IpjTf1AOMVS6lI0-mLPVyEQmUjpoVBG-ZP_tHaaxHLlr9A9gZL8YV7USPmwJs5oO8wn0NFyifPNFffshik0EcUObNXF_ZHODDFay75I_MBw7rZzJ1TRjE45HBnhcdiOcXgbCEmIp-lZaeHeRugiI-JfIiZW5HoE\",\"qi\":\"duIDrCNbefMXni-mwhf-8pkkyexDeWd1qCFN_kWqdiqpteuUFAEB0iuw3nEvL54VhuIxNuDItG1DRfFa_rU24eX0tXIdd8iiDzrwIPJDd5uEvs_fAr8ra4GVB8lkj4adST3oC2ribT3rw_j0mhPFFbuHKKmDugTQJbJg4B5Q5HQ\"}";
    // 公钥
    public final static    String publicjson  = "{\"kty\":\"RSA\",\"n\":\"u8SyxKf2kLkmOKOU-mcbXQmacQDCPtxfMGKzYx6HWaGcCFbIrFDubGIWhe3GRP5uQqXekqwDtiqurdGfUzOLSSLfe7bmCmEgntNbF9bgk8lZUhzszmb4sGk6VK4YiOiTWGYWn_7jyKyF_OXEpXY4C3WWWsZwQfLPNUYfVZE76o1MXT9F3622RhLSPOFVqJYL6RlzllvNc2PdfzVEBnFU4wKszT0n9J8ZrNAnlNUxOXi7Y78fLqQks60ERznZwytwB8krydQGkjH9y9pf70QFJW228mUxXHnPhG87Gi2eE62TardkBCvQcm4TJlEB5dnmhFYFhRkAR6IznUAjtkFZIw\",\"e\":\"AQAB\"}";

    /**
     * 生成token
     * @param userId 用户id
     * @param username 用户名字
     * @return
     */
    public static String sign(Long userId,String username) throws JoseException {

        // 1、 创建jwtclaims  jwt内容载荷部分
        JwtClaims claims = new JwtClaims();
        // 是谁创建了令牌并且签署了它
        claims.setIssuer("abcd");
        // 令牌将被发送给谁
        claims.setAudience("audience");
        // 失效时间长 （从现在开始10分钟）
        claims.setExpirationTimeMinutesInTheFuture(10000);
        // 令牌唯一标识符
        claims.setGeneratedJwtId();
        // 当令牌被发布或者创建现在
        claims.setIssuedAtToNow();
        // 再次之前令牌无效
        claims.setNotBeforeMinutesInThePast(2);
        // 主题
        claims.setSubject("subject");
        // 可以添加关于这个主题得声明属性
        claims.setClaim("userId",userId);
        claims.setClaim("username",username);

        // 2、签名
        JsonWebSignature jws = new JsonWebSignature();
        //赋值载荷
        jws.setPayload(claims.toJson());

        // 3、jwt使用私钥签署
        PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privatejson)).getPrivateKey();
        jws.setKey(privateKey);

        // 4、设置关键 kid
        jws.setKeyIdHeaderValue("keyId");

        // 5、设置签名算法
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        // 6、生成jwt
        String jwt = jws.getCompactSerialization();

        return jwt;

    }


    /**
     * 解密token
     *
     * @param token
     */
    public static void checkJwt(String token) throws JoseException {

        // 1、引入公钥
        PublicKey publicKey = new RsaJsonWebKey(JsonUtil.parseJson(publicjson)).getPublicKey();

        // 2、使用jwtcoonsumer  验证和处理jwt
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime() //过期时间
                .setAllowedClockSkewInSeconds(30) //允许在验证得时候留有一些余地 计算时钟偏差  秒
                .setRequireSubject() // 主题生命
                .setExpectedIssuer("abcd") // jwt需要知道谁发布得 用来验证发布人
                .setExpectedAudience("audience") //jwt目的是谁 用来验证观众
                .setVerificationKey(publicKey) // 用公钥验证签名  验证密钥
                .setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256))
                .build();
        try {
            // 3、验证jwt 并将其处理为 claims
            JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
            System.out.println(jwtClaims);
        } catch (InvalidJwtException e) {
            throw new RuntimeException(e);
        }


    }


    public static void main(String[] args) throws JoseException {
//        {"kty":"RSA","n":"u8SyxKf2kLkmOKOU-mcbXQmacQDCPtxfMGKzYx6HWaGcCFbIrFDubGIWhe3GRP5uQqXekqwDtiqurdGfUzOLSSLfe7bmCmEgntNbF9bgk8lZUhzszmb4sGk6VK4YiOiTWGYWn_7jyKyF_OXEpXY4C3WWWsZwQfLPNUYfVZE76o1MXT9F3622RhLSPOFVqJYL6RlzllvNc2PdfzVEBnFU4wKszT0n9J8ZrNAnlNUxOXi7Y78fLqQks60ERznZwytwB8krydQGkjH9y9pf70QFJW228mUxXHnPhG87Gi2eE62TardkBCvQcm4TJlEB5dnmhFYFhRkAR6IznUAjtkFZIw","e":"AQAB"}
//        {"kty":"RSA","n":"u8SyxKf2kLkmOKOU-mcbXQmacQDCPtxfMGKzYx6HWaGcCFbIrFDubGIWhe3GRP5uQqXekqwDtiqurdGfUzOLSSLfe7bmCmEgntNbF9bgk8lZUhzszmb4sGk6VK4YiOiTWGYWn_7jyKyF_OXEpXY4C3WWWsZwQfLPNUYfVZE76o1MXT9F3622RhLSPOFVqJYL6RlzllvNc2PdfzVEBnFU4wKszT0n9J8ZrNAnlNUxOXi7Y78fLqQ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0EcUObNXF_ZHODDFay75I_MBw7rZzJ1TRjE45HBnhcdiOcXgbCEmIp-lZaeHeRugiI-JfIiZW5HoE","qi":"duIDrCNbefMXni-mwhf-8pkkyexDeWd1qCFN_kWqdiqpteuUFAEB0iuw3nEvL54VhuIxNuDItG1DRfFa_rU24eX0tXIdd8iiDzrwIPJDd5uEvs_fAr8ra4GVB8lkj4adST3oC2ribT3rw_j0mhPFFbuHKKmDugTQJbJg4B5Q5HQ"}
        //生成公钥和私钥
//        RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
//        // 生成公钥
//        String publicjson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
//        // 生成私钥
//        String privatejson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
//        System.out.println(publicjson);
//        System.out.println(privatejson);

//String itbaizhan = sign(1001L, "itbaizhan");

        checkJwt("eyJraWQiOiJrZXlJZCIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJhYmNkIiwiYXVkIjoiYXVkaWVuY2UiLCJleHAiOjE3MDAyMTMzMjksImp0aSI6IkFFT3NvVmI5X2d6WkI5aXVUcUdyRFEiLCJpYXQiOjE3MDAyMTI3MjksIm5iZiI6MTcwMDIxMjYwOSwic3ViIjoic3ViamVjdCIsInVzZXJJZCI6MTAwMSwidXNlcm5hbWUiOiJhZG1pbiJ9.O0bB-_O2oEZI9Hzoq2wY9bE9WeZZth6SN5DDosRbcjy5Ng9ANtmRNn42ei1_6mqtsAdVdfh9d-VQJnIuNkZFuS12O-lVyFQwCn1_aqqCdPKEnwabAoV_F325ZVoURzJw8vZCgCt5etDQMkuR3Ki01_ClYBlSq5JubNIf_6vOSq4CtoeKJ5HZUY0xMjisWGwL-GhNYSJlrVfI9D1wqBIoOJP2lJ2YUFfsbU_t7Qhzt9bWlCC6zdR5RkPU04OtNeCOSAZCg9YRxmq2UiJ1tIJ3Oub6gZo-TCNzo7Zzx6dJ1rgw7nZr0N_oO0RnqxDnRWjOuk3RbOPG6tKuyR7j_bFPuw");


    }


}
